/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 标题 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) { PAR = $.par } else if ($.hasOwnProperty('script_parameter')){ PAR = JSON.parse($.script_parameter); }
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({ table: "pdm_aimdfm_task", data: { current_process_title: $.process_title }, where: { id: $.task_id } });
	}
}
var Status = 'ok';
var resultData = [];
var par = PAR;
var default_par = {
    step: "unit.+",
    step2:"unit",
	auto_save: "No",
	units:"mm"
}
for(var key in default_par){ if (!par.hasOwnProperty(key) || par[key] == ""){ par[key] = default_par[key] }}
var job = Job;
try {
	if(_.isEmpty(job)){throw "参数job不存在"} else { job = job.toLowerCase() }
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){ if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" } else { GEN.checkInout({job:job,mode:"out"}) } }
	var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig")
		return reg.test(step)
	})
    if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}


    var matrix = GEN.getMatrix({job:job})
    var work_layers = Object.keys(matrix).filter(function(key) {
        var info = matrix[key]
        return info.layer_type == "signal" && info.context == "board"
    })

    // 获取铜厚
    var ret = IKM.crud('selectArrayMap', {
        table: "pdm_job_stack_layers",
        field: ["layer_name","raw_thk"],
        where: {job_id:JobId}
	}).filter(function(item){return item.layer_name})
    var layerCount = IKM.get_jobinfo({jobid: JobId,jobinfo:"layer_count"}) || GEN.getLayerCount({job:job})
    var info = {};
    
    ret.map(function(row) {
        var layer = getRow(row.layer_name,layerCount) 
        var raw_thk = row.raw_thk
        if (raw_thk >= 18 && raw_thk < 35) {
            info[layer] = {
                min_line_width: 115,
                min_line_space: 120
            }
        } else if (raw_thk >= 35 && raw_thk < 70) {
            info[layer] = {
                min_line_width: 130,
                min_line_space: 130
            }
        } else if (raw_thk >= 70 && raw_thk < 105) {
            info[layer] = {
                min_line_width: 210,
                min_line_space: 150
            }
        } else if (raw_thk >= 105) {
            info[layer] = {
                min_line_width: 350,
                min_line_space: 170
            }
        }
    })
    stepList.forEach(function(step) {
        GEN.openStep({ job: job, name: step });
        GEN.clearLayers(); //清除层显示
        GEN.affectedLayer({ mode: 'all', affected: 'no' }); //设置影响层全部不影响
        GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
        GEN.units({ type: par.units }); //单位初始化
        GEN.zoomHome(); //窗口显示回到原始位置
        GEN.selClearFeature()
        work_layers.forEach(function(layer){
            if(info[layer]){
                GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
                var profile = GEN.getProfileLimits({job:job,step:step,units:"mm"})
                var shapes = getArea(profile)
                GEN.selectByFilter({attribute:[{attribute:".string", text:"tmp_surface"}]})
                if(GEN.getSelectCount() > 0) {GEN.selDelete()}
                shapes.forEach(function(rect) {
                    GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
                    GEN.selectByFilter({attribute:[{attribute:".string", text:"tmp_surface"}]})
                    if(GEN.getSelectCount() > 0) {GEN.selDelete()}
                    rect.forEach(function(item) { GEN.addRectangle(item) })
                    var tmp_layer = layer + "_tmp"
                    if(GEN.isLayerExists({job:job, layer:tmp_layer})){GEN.deleteLayer({job:job,layer:[tmp_layer]})}
                    if(GEN.isLayerExists({job:job, layer:"isl_lyr"})){GEN.deleteLayer({job:job,layer:["isl_lyr"]})}
                    if(GEN.isLayerExists({job:job, layer:"hole_lyr"})){GEN.deleteLayer({job:job,layer:["hole_lyr"]})}
                    if(GEN.isLayerExists({job:job, layer:"hole_lyr_2"})){GEN.deleteLayer({job:job,layer:["hole_lyr_2"]})}
                    GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer,invert:'no',dx:0,dy:0,size:0})
                    GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
                    GEN.COM("sel_contourize,accuracy=0,break_to_islands=yes,clean_hole_size=0,clean_hole_mode=x_and_y")
                    GEN.COM("sel_break_isl_hole,islands_layer=isl_lyr,holes_layer=hole_lyr")
                    GEN.workLayer({name:"hole_lyr",display_number:2,clear_before:'yes'})
                    GEN.selCopyOther({dest:'layer_name',target_layer:"hole_lyr_2",invert:'no',dx:0,dy:0,size:0})
                    GEN.workLayer({name:"hole_lyr_2",display_number:2,clear_before:'yes'})
                    GEN.selResize({size: -150})
                    GEN.workLayer({name:"hole_lyr",display_number:2,clear_before:'yes'})
                    GEN.selRefFeat({layers:"hole_lyr_2",use:"filter",mode:"touch"})
                    if(GEN.getSelectCount() > 0) {GEN.selDelete()}
                    GEN.selMoveOther({target_layer:layer,invert:'no',dx:0,dy:0,size:50})
                    GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
                    if(GEN.isLayerExists({job:job, layer:tmp_layer})){GEN.deleteLayer({job:job,layer:[tmp_layer]})}
                    if(GEN.isLayerExists({job:job, layer:"isl_lyr"})){GEN.deleteLayer({job:job,layer:["isl_lyr"]})}
                    if(GEN.isLayerExists({job:job, layer:"hole_lyr"})){GEN.deleteLayer({job:job,layer:["hole_lyr"]})}
                    if(GEN.isLayerExists({job:job, layer:"hole_lyr_2"})){GEN.deleteLayer({job:job,layer:["hole_lyr_2"]})}
                })
                GEN.selectByFilter({attribute:[{attribute:".string", text:"tmp_surface"}]})
                if(GEN.getSelectCount() > 0) {GEN.selDelete()}
            }
        })
    })
   

	// 保存 
	if(/yes/ig.test(par.auto_save)){GEN.checkInout({job:job,mode:"out"}); GEN.saveJob({ job: job });GEN.checkInout({job:job,mode:"in"});GEN.closeJob({job:job});} else {GEN.checkInout({job:job,mode:"in"})}
	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) { Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else { resultData.push({ type: "info", title: "操作完成, 请注意检查!" }); return {status: Status,result_data: resultData}; }
	}else { return "Done" }
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"));IKM.msg(e);Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function getArea(profile) {
    var xmin = Number(profile.xmin)
    var ymin = Number(profile.ymin)
    var xmax = Number(profile.xmax)
    var ymax = Number(profile.ymax)
    return [
        [{
            x1:xmin,
            y1:(ymax - ymin)/2 + ymin + 10,
            x2:xmax,
            y2:ymax,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        },{
            x1:(xmax - xmin)/2 + xmin + 10,
            y1:ymin,
            x2:xmax,
            y2:(ymax - ymin)/2 + ymin + 10,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        }],
        [{
            x1:xmin,
            y1:(ymax - ymin)/2 + ymin + 10,
            x2:xmax,
            y2:ymax,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        },{
            x1:xmin,
            y1:ymin,
            x2:(xmax - xmin)/2 + xmin - 10,
            y2:(ymax - ymin)/2 + ymin + 10,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        }],
        [{
            x1:xmin,
            y1:ymin,
            x2:xmax,
            y2:(ymax - ymin)/2 + ymin - 10,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        },{
            x1:xmin,
            y1:(ymax - ymin)/2 + ymin - 10,
            x2:(xmax - xmin)/2 + xmin - 10,
            y2:ymax,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        }],
        [{
            x1:xmin,
            y1:ymin,
            x2:xmax,
            y2:(ymax - ymin)/2 + ymin - 10,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        },{
            x1:(xmax - xmin)/2 + xmin + 10,
            y1:(ymax - ymin)/2 + ymin - 10,
            x2:xmax,
            y2:ymax,
            polarity:"negative",
            attributes:[{attribute:".string", text:"tmp_surface"}]
        }]
    ]
}

function getRow( signal1, layerCount) {
    signal1 = Number(signal1.slice(1)) 
    if (signal1 == 1) {
        return "gtl"
    } else if (signal1 == layerCount) {
        return "gbl"
    } else {
        return "l" + signal1
    }
}
